package cn.wolfcode.crm.shiro;

import cn.wolfcode.crm.util.JsonResult;
import com.alibaba.fastjson.JSON;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.web.filter.authc.FormAuthenticationFilter;
import org.springframework.stereotype.Component;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import java.io.IOException;

/**
 * Created by GG on 2020/3/20.
 * 因为异步请求是没办法搞重定向,所以会调用 FormAuthenticationFilter 中的 onLoginFailure 和 onLoginSuccess 方法对失
 败和成功的结果进行处理
 @component （把普通pojo实例化到spring容器中，相当于配置文件中的<bean id="" class=""/>）
 */
@Component("crmFormAuthenticationFilter")
public class AjaxFormAuthenticationInfoFilter extends FormAuthenticationFilter{
    @Override
    protected boolean onLoginSuccess(AuthenticationToken token, Subject subject,
                                     ServletRequest request, ServletResponse response) throws Exception {
        //调用jsonresult对象
        JsonResult json = new JsonResult();
        //使用response对象输出数据(json字符串)
        response.setContentType("application/json;charset=utf-8");
        //写入数据,转成json对象
        response.getWriter().print(JSON.toJSONString(json));
        return false ;//我们在上面已经处理完,所以不用放行,不放行
    }

    @Override
    protected boolean onLoginFailure(AuthenticationToken token, AuthenticationException e,
                                     ServletRequest request, ServletResponse response) {
        //异常信息要打印
        e.printStackTrace();
        String msg="登录异常,请联系管理员";
        if (e instanceof UnknownAccountException){//用户名异常,没有这个账号
            msg="账号密码不存在";
        }else if (e instanceof IncorrectCredentialsException){//密码异常,密码错误
            msg = "密码错误";
        }
        JsonResult json = new JsonResult(false, msg);
        //shiyong response对象输出数据(json字符串)
        response.setContentType("application/json;charset=utf-8");
        try {
            response.getWriter().print(JSON.toJSONString(json));
        } catch (IOException e1) {
            e1.printStackTrace();
        }
        return false;

    }
}
